package com.ebraga.trackerclub.android.dao.core.webservice;

import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.ebraga.trackerclub.android.dao.api.webservice.ParameterWSDao;
import com.ebraga.trackerclub.android.dao.entity.ParameterAndroid;
import com.ebraga.trackerclub.android.exception.BackofficeConnectionException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeConnectionWebServicesException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeIllegalArgumentDaoException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeInvalidURLWebServicesException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeWebServicesException;
import com.ebraga.trackerclub.android.util.webservice.HTTPSClientWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

public abstract class ParameterWSDAOImpl implements ParameterWSDao {

	private HTTPSClientWrapper<String> httpsClientWrapper;
	private String url;
	
	public void setHTTPSClientWrapper(HTTPSClientWrapper<String> httpsClientWrapper) {
		this.httpsClientWrapper = httpsClientWrapper;
	}

	public void setURL(String url) {
		this.url = url;
	}

	@Override
	public List<ParameterAndroid> retrieveParametersOnline(List<String> parameterNameList) throws BackofficeWebServicesException, 
		BackofficeInvalidURLWebServicesException, BackofficeConnectionWebServicesException, BackofficeIllegalArgumentDaoException {
		if(httpsClientWrapper == null)
			throw new BackofficeIllegalArgumentDaoException("Client cannot be null.");
		
		if(url == null)
			throw new BackofficeIllegalArgumentDaoException("URL cannot be null.");
		
		if(parameterNameList == null || parameterNameList.isEmpty()) {
			throw new BackofficeIllegalArgumentDaoException("ParameterNameList cannot be null or empty.");
		}

		String response = "";
		try {
			new URL(url);
			response = httpsClientWrapper.doPost(url, parameterNameList);
			
			Type listType = new TypeToken<ArrayList<ParameterAndroid>>() {}.getType();
			List<ParameterAndroid> responseList = new Gson().fromJson(response, listType);
	
			return responseList;
			
		} catch (MalformedURLException e) {
			throw new BackofficeInvalidURLWebServicesException("Innválid URL: "+url, e);
		} catch (JsonParseException e) {
			throw new BackofficeIllegalArgumentDaoException("The response not represents the expected parameter 'List<ParameterAndroid>', Response: "+response);
		} catch (BackofficeConnectionException e) {
			throw new BackofficeConnectionWebServicesException(e);
		} catch (Throwable e) {
			throw new BackofficeWebServicesException(e);
		}
	}

}
